import json
import time

from commonTool.logs.logs_wrapper import LogUtil
from commonTool.properties_tool import PropertiesTool
from manager.api.device import DeviceApi
from manager.config.Base_File_Config import BASE_PATH
from manager.tool import TestTool as testTool

read = PropertiesTool(BASE_PATH + '/config/environment.properties')

logs = LogUtil()


class EventMessagePushApi:
    """
    事件消息推送工具
    """

    user_progress = []

    @staticmethod
    def __report_360_api(dateKey, dateValue, is_sign):
        """
        360事件消息推送接口
        :param dateKey: 事件消息推送时间
        :param dateValue: 事件消息推送时间
        :return:
        """
        api = DeviceApi()
        r = api.api_eventmessage_deviceeventnotify_360(dateKey, dateValue, is_sign)

        # 打印输出结果
        testTool.printAndLogResponse(r)

    @staticmethod
    def __get_content_list(message, start_key, end_key) -> list:
        """
        获取360事件消息推送文件中的内容
        :param start_key: 开始关键字
        :param end_key: 结束关键字
        :return:请求数据
        """
        content = message
        print(content)
        notity_list = []
        while content.find(start_key) != -1:
            start_index = content.find(start_key) + len(start_key)
            end_index = content.find(end_key)
            json_str = content[start_index:end_index]
            notity_list.append(json_str)
            content = content[end_index + len(end_key):]

        return notity_list

    @logs
    def start_all(self, message, user_id, env='dev', is_sign=False, up_time=1000):
        """
        启动事件消息推送
        :param user_id:     用户id
        :param message: 事件消息推送文本
        :param env: 环境
        :param is_sign: 是否需要签名
        :param up_time: 推送间隔时间
        :return:
        """
        # notitys = EventMessagePushApi.__get_notity_list(file_path)
        notitys = message

        self.set_progress(user_id, 1, 1)
        # 切换环境
        read.set('ENVIRONMENT', env)
        data_key = ["msg", "sign"]
        try:
            notity_json = json.loads(message)
        except Exception as e:
            logs.error(e)
            return e
        data_value = [notity_json.get(data_key[0]), notity_json.get(data_key[1])]
        self.__report_360_api(data_key, data_value, is_sign)

    @logs
    def start_custom(self, message, start_key, end_key, user_id, env='dev', is_sign=False, up_time=1000):
        """
        启动事件消息推送 自定义匹配格式
        :param user_id:     用户id
        :param message: 事件消息推送文本
        :param start_key: 开始匹配字符
        :param end_key:   结束匹配字符
        :param env: 环境
        :param is_sign: 是否需要签名
        :param up_time: 推送间隔时间
        :return:
        """
        notitys = self.__get_content_list(message, start_key, end_key)
        currt_num = 1
        # 切换环境
        read.set('ENVIRONMENT', env)
        data_key = ["msg", "sign"]
        for n in notitys:
            self.set_progress(user_id, currt_num, len(notitys))
            progress = int(self.get_progress(user_id) * 100)
            bre = '-' * progress
            # print('\r' + f"loading... [{bre}] {progress} %", end='', flush=True)
            currt_num += 1
            notity_json = json.loads(n)
            data_value = [notity_json.get(data_key[0]), notity_json.get(data_key[1])]
            self.__report_360_api(data_key, data_value, is_sign)
            time.sleep(up_time / 1000)

    @logs
    def start_log(self, message, user_id, env='dev', is_sign=True, up_time=1000):
        """
        启动事件消息推送
        :param user_id:     用户id
        :param message: 事件消息推送文本
        :param env: 环境
        :param is_sign: 是否需要签名
        :param up_time: 推送间隔时间
        :return:
        """
        start_key = '360订阅消息异步数据：'
        end_key = '| \'\''
        self.start_custom(message, start_key, end_key, user_id, env, is_sign, up_time)

    def set_progress(self, user_id, current_num, total_num):
        is_has = False
        for key in self.user_progress:
            if key.get("user_id") == user_id:
                key["current"] = current_num
                key["total"] = total_num
                is_has = True
        if not is_has:
            self.user_progress.append({"user_id": user_id, "current": current_num, "total": total_num})

    def get_progress(self, user_id):
        for key in self.user_progress:
            if key.get("user_id") == user_id:
                current = key.get("current")
                total = key.get("total")
                return current / total

    def clear_progress(self, notitys, user_id):
        currt_num = 1
        for n in notitys:
            time.sleep(1)
            self.set_progress(user_id, currt_num, len(notitys))
            progress = int(self.get_progress(user_id) * 50)
            progress_str = (' ' * (50 - progress))
            loading_str = "SUCCESS " if progress == 50 else "loading "
            # print(progress)
            # print(loading_str)
            print(
                '\r' + f"{loading_str} {'-' * progress}{progress_str}  {progress * 2}%",
                end='', flush=True)
            currt_num += 1

    def bar(self):
        from rich.progress import track
        for step in track(range(30)):
            time.sleep(0.5)


# if __name__ == '__main__':
# a = EventMessagePushApi()
# notitys = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4,
#            5, 6, 7, 8, 9, 10]
# a.clear_progress(notitys, 123)
# a.bar()
if __name__ == '__main__':
    while 1:
        content = r"""     
    【360订阅消息验签】数据获取成功: {"msg":"{\"message_id\":\"1706837231681872-87146163478881-22\",\"message_type\":4,\"message_create_time\":1706837231688,\"message_info\":{\"device_ip\":\"111.0.75.65\",\"device_name\":\"QC3202400000060\",\"last_time\":1706837231683,\"payload\":{\"action\":\"dsl.event.post.ObjectMotion\",\"data\":{\"CloudEventID\":\"\",\"EventID\":\"170683723135684271\",\"EventTime\":\"1706837231356\",\"ExtInfo\":\"{\\\"canPush\\\":1,\\\"cloudRecordType\\\":0,\\\"cloudExt\\\":\\\"{\\\\\\\"cloudRecordType\\\\\\\":4,\\\\\\\"cloudRecordDays\\\\\\\":1}\\\",\\\"fastPush\\\":0}\",\"ImageInfo\":\"\",\"VideoInfo\":\"\"},\"id\":18,\"version\":1},\"product_key\":\"f157af439d2c\",\"topic\":\"$qihoo/f157af439d2c/QC3202400000060/dsl/event/post/ObjectMotion\"},\"extra\":{\"all_event_types\":[{\"action\":\"dsl.event.post.ObjectMotion\",\"name\":\"人/宠移动\"}],\"dsy_message_id\":\"1706837231-b883c9f3637db639fc3fec5e9935763e\",\"expire_period\":1706923631,\"image_info\":\"\",\"source\":\"device\"}}","sign":"4db8e63e5e3966d23cb49fc156d77d96"} | '' 
    """
        a = EventMessagePushApi()
        start_key = "【360订阅消息验签】数据获取成功:"
        end_key = '| \'\''
        a.start_custom(content, start_key, end_key, 1768189004962676736, is_sign=False, env="release", up_time=3000)
